package gin.dev.update;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.vstore.activities.SceneDetailItemActivity;

public class UpdateTask {
	private static final String TAG = "TAG";
	public static void Update(Context context, String packagename, String version, String url) {
		// check app con tren may khong
		String oldversion = GetAppVersion(context, packagename);
		if(oldversion.equals("none") == true)
		{
			Log.d(TAG, "app " + packagename +" do not exist!");
			return;
		}

		// check version app la cu hay moi
		if(CheckNewVersion(version, oldversion) == false)
		{
			Log.d(TAG, "app version " + version + " do not out off date!");
			return;
		}

		// download apk version moi
		Log.d(TAG, "link apk " + url);
		final Context cont = context;
		final String fpackageName = packagename;
		DownloadTask task = new DownloadTask(context, null, new IOnDownload() {
			
			@Override
			public void OnFinished() {
				// TODO Auto-generated method stub
				String path = Environment.getExternalStorageDirectory()
						.getAbsoluteFile()
						+ "/Download/" + fpackageName + ".apk";
				File file = new File(path);
				
				 Intent intent = new Intent(Intent.ACTION_VIEW);
				 intent.setDataAndType(Uri.fromFile(file),
				 "application/vnd.android.package-archive");
				 cont.startActivity(intent);
			}

			@Override
			public void OnError() {
				// TODO Auto-generated method stub
				
			}
		});
		DownloadQuere.Add(context, task, -1, url, fpackageName);
	}

	public static String GetAppVersion(Context context, String targetPackage) {
		PackageManager pm = context.getPackageManager();
		String version = "none";
		try {
			PackageInfo info = pm.getPackageInfo(targetPackage,
					PackageManager.GET_META_DATA);
			version = info.versionName;
		} catch (NameNotFoundException e) {
			return version;
		}
		return version;
	}
	
	public static boolean CheckNewVersion(String newVersion, String oldVersion)
	{
		String nVersion = newVersion.replace(".", "");
		String oVersion = oldVersion.replace(".", "");
		int n1 = nVersion.length();
		int n2 = oVersion.length();
		int n = Math.min(n1, n2);
		for(int i=n;i<n1;i++)
			nVersion = nVersion + "0";
		for(int i=n;i<n2;i++)
			oVersion = oVersion + "0";
		try
		{
			float a = Float.parseFloat(nVersion);
			float b = Float.parseFloat(oVersion);
			if(a > b)
				return true;
		}
		catch(Exception ex)
		{
			Log.i("Test", ex.getMessage());
		}
		return false;
	}
}
